<template>
  <div class="observer-video">
    <slot name="checkbox"></slot>
    <div v-for="stream in remoteStream" id="remoteVideo" :key="stream.id">
      <div class="streamvideo" :id="stream.id + 'div'">
        <video
          autoplay="autoplay"
          muted
          controls
          class="wh left"
          :id="stream.id"
        ></video>
        <img
          :src="imgSrc"
          class="muteimg"
          @click="unmuted(stream.id)"
          :id="'img' + stream.id"
        />
        <p><span>座席工号：</span>{{ stream.agentNo }}</p>
        <!-- <VideoStatus :stream="stream"></VideoStatus> -->
      </div>
    </div>
  </div>
</template>

<script>
require('../../../public/js/irtcClient');
require('../../../public/js/irtc')
import VideoStatus from './VideoStatus'
export default {
  name: 'observerVideo',
  components: {
    VideoStatus
  },
  props: {
    token: {
      type: String,
      default: ''
    },
    agentNo: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      remoteStream: [],
      streamType: 'mixed',
      imgSrc: require('../../static/images/mute.png'),
      Authorization: null,
      joinSuccess: false,
      subscriptions: new Map(),
      allstats: [],
      intervalfunction: null,
      irtcClient:null
    };
  },

  destroyed() {
    if (this.intervalfunction != null) {
      window.clearInterval(intervalfunction);
    }
    this.leave();
  },
  mounted() {
    let { ConferenceClient } = IRtc.Conference;
    let turnserverUrl = localStorage.getItem('turnserverUrl');
    let turnserverCredential = localStorage.getItem('turnserverCredential');
    let turnserverUsername = localStorage.getItem('turnserverUsername');
    let ccOptions = {
      rtcConfiguration: {
        iceServers: [
          {
            urls: [turnserverUrl],
            credential: turnserverCredential,
            username: turnserverUsername
          }
        ]
      }
    };
     this.irtcClient = new ConferenceClient(ccOptions);
    if (this.token) {
      this.join();
    }
  },
  methods: {
    /*取消静音*/
    unmuted(id) {
      var myVid = document.getElementById(id);
      if (myVid.muted) {
        this.imgSrc = require('../../static/images/unmute.png');
        myVid.muted = false;
      } else {
        this.imgSrc = require('../../static/images/mute.png');
        myVid.muted = true;
      }
    },

    /*加入房间*/
    join() {
      var self = this;
      this.irtcClient
        .join(this.token)
        .then(function (resp) {
          console.log('join success', resp);
          self.joinSuccess = true;
          const streams = resp.remoteStreams.filter(
            (stream) => stream.source.video === self.streamType
          );
          self.roomremotestream(streams);
          self.addclientEvent(self.irtcClient);
        })
        .catch(function (error) {
          console.log(error);
          self.$Message.error(error);
        });
    },

    /*房间流的处理*/
    roomremotestream(remoteStreams) {
      var self = this;
      remoteStreams.forEach(function (stream, index) {
        console.log(index);
        stream.agentNo = self.agentNo;
        console.log(stream);
        // if (stream.origin){
        //   //非mix流
        //   if (stream.settings.video != undefined){
        //     //audio流不显示UI,,video流显示UI
        //     self.remoteStream.push(stream);
        //   }
        //   self.substream(stream);
        // }
        if (stream.settings.video != undefined) {
          //audio流不显示UI,,video流显示UI
          self.remoteStream.push(stream);
        }
        self.substream(stream);
      });
    },

    /*给当前client添加监听事件*/
    addclientEvent(client) {
      let streamaddedListener = (eve) => {
        let remoteStream = eve.stream;
        console.log('add stream');
        console.log(remoteStream);
        if (remoteStream.origin) {
          if (remoteStream.settings.video != undefined) {
            //audio流不显示UI,,video流显示UI
            this.remoteStream.push(remoteStream);
          }
          this.substream(remoteStream);
        }
      };
      let participantjoinedListener = (eve) => {
        console.log('new participant joined:', eve);
      };

      let messagereceivedListener = (eve) => {
        console.log('new message received: ', eve);
      };

      let serverdisconnectedListener = () => {
        console.log('server disconnected');
      };

      client.addEventListener('streamadded', streamaddedListener);
      client.addEventListener('participantjoined', participantjoinedListener);
      client.addEventListener('messagereceived', messagereceivedListener);
      client.addEventListener('serverdisconnected', serverdisconnectedListener);
    },

    /*订阅当前房间里面的流*/
    substream(stream) {
      console.log('开始订阅');
      var self = this;
      //判断流的source
      let audio = true;
      let video = true;
      if (stream.settings.audio == undefined) {
        audio = false;
      }
      if (stream.settings.video == undefined) {
        video = false;
      }
      let options = {
        audio: audio,
        video: video
      };
      console.log(this.irtcClient, options, stream);
      this.irtcClient.subscribe(stream, options).then(
        (subscription) => {
          console.log('订阅成功');
          console.log(stream.id);
          console.log(subscription);
          if (video) {
            self.displayremotestream(stream);
          }
          self.streamEvent(stream); //给流添加监听
          var streamId = stream.id;
          self.subscriptions.set(stream.id, subscription);
          console.log('订阅成功,', self.subscriptions);
          // self.getstatswithStreamId(streamId);//定时获取订阅的流数据
        },
        (err) => {
          self.$Message.error(err);
          console.log('subscribe failed');
          console.log(`subscribe ${stream.id} failed: ${err}`);
        }
      );
    },

    /*给流添加监听事件*/
    streamEvent(stream) {
      let enedListener = (event) => {
        console.log(`remote stream ${stream.id} is ended`);
        console.log(event);
        $('#' + stream.id).attr('style', 'display:none;');
        $('#' + stream.id + 'div').attr('style', 'display:none;');
        //this.remoteStream = this.removeArraybyid(this.remoteStream,stream);
      };
      stream.addEventListener('ended', enedListener);
    },

    /*删除数组中某一个id相同的元素*/
    removeArraybyid(_arr, _obj) {
      if (_arr) {
        var length = _arr.length;
        for (var i = 0; i < length; i++) {
          if (_arr[i].id == _obj.id) {
            if (i == 0) {
              _arr.shift(); //删除并返回数组的第一个元素
              return _arr;
            } else if (i == length - 1) {
              _arr.pop(); //删除并返回数组的最后一个元素
              return _arr;
            } else {
              _arr.splice(i, 1); //删除下标为i的元素
              return _arr;
            }
          }
        }
      }
      return _arr;
    },

    /*显示view*/
    displayremotestream(stream) {
      $('#' + stream.id).get(0).srcObject = stream.mediaStream;
    },

    leave() {
      var self = this;
      this.irtcClient.leave().then(
        () => {
          this.irtcClient.clearEventListener('streamadded');
          this.irtcClient.clearEventListener('participantjoined');
          this.irtcClient.clearEventListener('messagereceived');
          this.irtcClient.clearEventListener('serverdisconnected');
          this.irtcClient.clearEventListener('ended');
          // self.$toast('成功离开');
          self.joinSuccess = false;
          self.remoteStream = []; //删除已经订阅的任何流
          console.log('this.irtcClient leave success');
        },
        (err) => {
          //self.$toast('离开失败'+err);
          console.log('this.irtcClient leave failed: ', err);
        }
      );
    }
  }
};
</script>

<style scoped>
.observer-video {
    width: 33%;
    padding: 5px;
    position: relative;
}

.streamvideo {
  position: relative;
}
.streamvideo video {
  width: 100%;
}
.streamvideo img {
  position: absolute;
  bottom: 28%;
  right: 10%;
  width: 10%;
  z-index: 666;
}
.streamvideo p {
  text-align: center;
}
</style>
